//
//  XS_HangyeVC.swift
//  XueDao
//
//  Created by 韩云智 on 2020/12/10.
//

import UIKit
import RxSwift
import RxCocoa

class XS_HangyeVC: XS_BaseVC {
    lazy var tags: [XS_HomeTopM] = []
    lazy var total: [XS_HomeTopM] = []
    lazy var texts = ["点击进入行业频道", "拖拽可以排序", "点击添加行业频道 最多3个"]
    lazy var btns: [UIButton] = []
    var collection1: UICollectionView!
    var collection2: UICollectionView!
    lazy var canEdit = false
    override func upConfig() {
        modalPresentationStyle = .fullScreen
    }
    override func upView() {
        let close = XS_NoHighlightBtn()
        close.setBackgroundImage(UIImage(named: "icon_关闭"), for: .normal)
        view.addSubview(close)
        close.snp.makeConstraints({
            $0.width.height.equalTo(.scale*24)
            $0.left.equalTo(.scale*16)
            $0.top.equalTo(CGFloat.barHeight + 22)
        })
        close.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                self?.dismiss(animated: true)
            }).disposed(by: disposeBag)
        
        let tLab1 = UILabel.xsLabel(size: .scale*18, fontName: .semibold, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1), text: "我的行业")
        view.addSubview(tLab1)
        tLab1.snp.makeConstraints({
            $0.left.equalTo(.scale*16)
            $0.top.equalTo(.scale*16 + .barHeight + 44)
        })
        let dLab1 = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1), text: texts[0])
        view.addSubview(dLab1)
        dLab1.snp.makeConstraints({
            $0.left.equalTo(tLab1.snp.right).offset(.scale*8)
            $0.bottom.equalTo(tLab1.snp.bottom).offset(-.scale*2)
        })
        
        let btn = XS_NoHighlightBtn()
        btn.layer.cornerRadius = .scale*12
        btn.layer.borderWidth = .scale
        btn.layer.borderColor = #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1)
        btn.setTitle("编辑", for: .normal)
        btn.setTitle("完成", for: .selected)
        btn.setTitleColor(#colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1), for: .normal)
        btn.titleLabel?.font = .xsFont(name: .medium, .scale*12)
        view.addSubview(btn)
        btn.snp.makeConstraints({
            $0.width.equalTo(.scale*48)
            $0.height.equalTo(.scale*24)
            $0.centerY.equalTo(tLab1.snp.centerY)
            $0.right.equalTo(-.scale*16)
        })
        btn.rx.tap.asDriver()
            .map { !btn.isSelected }
            .drive(onNext: { [weak self] set in
                btn.isSelected = set
                dLab1.text = self?.texts[set ? 1 : 0]
                self?.canEdit = set
                self?.collection1.reloadData()
                if !set {
                    self?.save()
                }
            }).disposed(by: disposeBag)
        
        let tLab2 = UILabel.xsLabel(size: .scale*18, fontName: .semibold, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1), text: "更多行业")
        view.addSubview(tLab2)
        tLab2.snp.makeConstraints({
            $0.left.equalTo(.scale*16)
            $0.top.equalTo(.scale*248 + .barHeight + 44)
        })
        let dLab2 = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1), text: texts.last)
        view.addSubview(dLab2)
        dLab2.snp.makeConstraints({
            $0.left.equalTo(tLab2.snp.right).offset(.scale*8)
            $0.bottom.equalTo(tLab2.snp.bottom).offset(-.scale*2)
        })
        
        do {
            let flowLayout = JYEqualCellSpaceFlowLayout()
            flowLayout.cellType = .left
            flowLayout.betweenOfCell = .scale*16
//            flowLayout.itemSize = CGSize(width: .scale*104, height: .scale*32)
            flowLayout.minimumLineSpacing = .scale*16
            flowLayout.minimumInteritemSpacing = .scale*10
            flowLayout.sectionInset = UIEdgeInsets(top: .scale*16, left: .scale*16, bottom: 0, right: .scale*15)
            
            collection1 = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
            collection1.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
            collection1.bounces = false
            collection1.register(XS_HangyeCell.self, forCellWithReuseIdentifier: "cell")
            collection1.delegate = self
            collection1.dataSource = self
            
            let longPress = UILongPressGestureRecognizer()
            collection1.addGestureRecognizer(longPress)
            longPress.rx.event.asDriver()
                .drive(onNext: { [weak self] long in
                    guard let `self` = self, self.canEdit else { return }
                    //获取点击在collectionView的坐标
                    let point = long.location(in: self.collection1)
                    //从长按开始
                    if (long.state == .began) {
                        if let indexPath = self.collection1.indexPathForItem(at: point) {
                            self.collection1.beginInteractiveMovementForItem(at: indexPath)
                        }
                        //长按手势状态改变
                    } else if(long.state == .changed) {
                        self.collection1.updateInteractiveMovementTargetPosition(point)
                        //长按手势结束
                    } else if (long.state == .ended) {
                        self.collection1.endInteractiveMovement()
                        //其他情况
                    } else {
                        self.collection1.cancelInteractiveMovement()
                    }
                }).disposed(by: disposeBag)
        }
        view.addSubview(collection1)
        collection1.snp.makeConstraints({
            $0.top.equalTo(tLab1.snp.bottom)
            $0.bottom.equalTo(tLab2.snp.top)
            $0.left.right.equalToSuperview()
        })
        
        do {
            let flowLayout = JYEqualCellSpaceFlowLayout()
            flowLayout.cellType = .left
            flowLayout.betweenOfCell = .scale*16
//            flowLayout.itemSize = CGSize(width: .scale*104, height: .scale*32)
            flowLayout.minimumLineSpacing = .scale*16
            flowLayout.minimumInteritemSpacing = .scale*10
            flowLayout.sectionInset = UIEdgeInsets(top: .scale*16, left: .scale*16, bottom: 0, right: .scale*15)
            
            collection2 = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
            collection2.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
            collection2.bounces = false
            collection2.register(XS_HangyeTotalCell.self, forCellWithReuseIdentifier: "cell")
            collection2.delegate = self
            collection2.dataSource = self
        }
        view.addSubview(collection2)
        collection2.snp.makeConstraints({
            $0.top.equalTo(tLab2.snp.bottom)
            $0.left.right.bottom.equalToSuperview()
        })
//        XS_NetWork.requestJson("/industry/queryAllStatusApi")
        XS_NetWork.requestJson("/industry/queryAllIndustryBySearchType", parameters: ["searchType" : "curriculum"])
            .mapModels(type: XS_HomeTopM.self)
            .subscribe(onNext: { [weak self] models, resp in
                guard let `self` = self, resp.success else { return }
                self.total = models
                for (index,tagsSub) in self.tags.enumerated() {
                    if !self.total.contains(where: {$0.id == tagsSub.id}) {
                        self.tags.remove(at: index)
                    }
                }
                self.save()
                
                self.collection2.reloadData()
                self.collection1.reloadData()
            }).disposed(by: disposeBag)
    }

    func save() {
        _ = XS_NetWork.requestJson("/industry/updUserIndustry", parameters: ["ids":tags.compactMap({ $0.id })])
            .subscribe(onNext: { [weak self] resp in
                guard resp.success else { return }
                XS_Singleton.shared.changeHome?()
//                XS_Singleton.shared.changeKuaixue?()
                XS_Singleton.shared.changeZhengshu?(self?.tags ?? [])
            })
    }
}

extension XS_HangyeVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let text: String
        if collectionView == collection1 {
            text = tags[indexPath.item].name
        } else {
            text = total[indexPath.item].industryName
        }
        let width = min(text.size(withFont: .xsFont(.scale*14)).width + .scale*32, .screenWidth - .scale*32)
        return CGSize(width: max(.scale*104, width), height: .scale*32)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if collectionView == collection1 {
            return tags.count
        } else {
            return total.count
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionView == collection1 {
            let model = tags[indexPath.item]
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! XS_HangyeCell
            cell.up(model, enble: canEdit) { [weak self] id in
                if (self?.tags.count)! > 1 {
                    self?.tags.removeAll(where: { $0.id == id })
                    self?.save()
                    self?.collection1.reloadData()
                    self?.collection2.reloadData()
                } else {
                    self?.view.makeToast("请至少选择一个行业")
                }
            }
            return cell
        } else {
            let model = total[indexPath.item]
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! XS_HangyeTotalCell
            cell.up(model, enble: !tags.contains(where: { $0.id == model.id }))
            return cell
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
        (canEdit && collectionView === collection1)
    }
//    func collectionView(_ collectionView: UICollectionView, targetIndexPathForMoveFromItemAt originalIndexPath: IndexPath, toProposedIndexPath proposedIndexPath: IndexPath) -> IndexPath {
//        /* 两个indexpath参数, 分别代表源位置, 和将要移动的目的位置*/
//            //-1 是为了不让最后一个可以交换位置
//            if (proposedIndexPath.item == (tags.count - 1)) {
//                //初始位置
//                return originalIndexPath;
//            } else {
//            //-1 是为了不让最后一个可以交换位置
//                if (originalIndexPath.item == (tags.count - 1)) {
//                    return originalIndexPath;
//                }
//        //      移动后的位置
//                return proposedIndexPath;
//            }
//    }
    func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        let model = tags.remove(at: sourceIndexPath.item)
        tags.insert(model, at: destinationIndexPath.item)
        collectionView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if collectionView == collection2 {
            if tags.count < 3 {
                let model = total[indexPath.item]
                model.name = model.industryName
                tags.append(model)
                save()
                collection1.reloadData()
                collection2.reloadData()
            }
        }
    }
}
class XS_HangyeCell: XS_BaseCCell {
    lazy var lab = UILabel.xsLabel(size: .scale*14, fontName: .regular, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1))
    lazy var btn = XS_NoHighlightBtn()
    func up(_ model: XS_HomeTopM, enble: Bool, block: ((Int)->())?) {
        reuseDisposeBag = DisposeBag()
        isUserInteractionEnabled = enble
        lab.text = model.name
        lab.textAlignment = enble ? .left : .center
        btn.isHidden = !enble
        btn.rx.tap.asDriver()
            .drive(onNext: {
                block?(model.id)
            }).disposed(by: reuseDisposeBag)
    }
    override func upView() {
        contentView.layer.cornerRadius = .scale*16
        contentView.layer.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.968627451, blue: 0.968627451, alpha: 1)
        contentView.addSubview(lab)
        lab.snp.makeConstraints { maker in
            maker.top.bottom.equalToSuperview()
            maker.left.equalTo(.scale*8)
            maker.right.equalTo(-.scale*8)
        }
        btn.setImage(UIImage(named: "icon_12px_删除_1"), for: .normal)
        contentView.addSubview(btn)
        btn.snp.makeConstraints { maker in
            maker.width.equalTo(.scale * 22)
            maker.height.equalTo(.scale*32)
            maker.right.equalToSuperview()
            maker.centerY.equalToSuperview()
        }
    }
}
class XS_HangyeTotalCell: XS_BaseCCell {
    lazy var lab = UILabel.xsLabel(size: .scale*14, fontName: .regular)
    lazy var imgV = UIImageView()
    func up(_ model: XS_HomeTopM, enble: Bool) {
        isUserInteractionEnabled = enble
        lab.text = model.industryName
        lab.textColor = enble ? #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1) : #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1)
        imgV.image = UIImage(named: enble ? "icon_12px_添加" : "icon_12px_已添加")
    }
    override func upView() {
        contentView.layer.cornerRadius = .scale*16
        contentView.layer.borderWidth = .scale
        contentView.layer.borderColor = #colorLiteral(red: 0.9411764706, green: 0.9490196078, blue: 0.968627451, alpha: 1)
        contentView.addSubview(lab)
        contentView.addSubview(imgV)
        lab.snp.makeConstraints({
            $0.centerY.equalToSuperview()
            $0.left.equalTo(.scale*8)
            $0.right.lessThanOrEqualTo(imgV.snp.left).offset(-.scale*4)
        })
        imgV.snp.makeConstraints({
            $0.width.height.equalTo(.scale*12)
            $0.centerY.equalToSuperview()
            $0.right.equalTo(-.scale*8)
        })
    }
}
